package com.party.admin.biz.crowdfundMultiple;

import com.party.admin.biz.file.FileBizService;
import com.party.core.exception.BusinessException;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.activity.ActivityDetail;
import com.party.core.model.activity.ActivityInput;
import com.party.core.model.crowdfund.CrowdfundEvent;
import com.party.core.model.member.PackageCount;
import com.party.core.model.notify.InstanceWay;
import com.party.core.model.notify.TargetTemplate;
import com.party.core.model.system.TargetType;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.activity.biz.ActivityDetailBizService;
import com.party.core.service.activity.biz.ActivityInfoBizService;
import com.party.core.service.activity.biz.CrowfundResourceBizService;
import com.party.core.service.crowdfund.ICrowdfundEventService;
import com.party.core.service.crowdfund.IProjectService;
import com.party.core.service.crowdfund.ITargetTemplateService;
import com.party.core.service.member.IPackageCountService;
import com.party.notify.notifyPush.servce.INotifySendService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @ClassName ActivityMultipleBizService
 * @Description 多场活动业务处理
 * @Author yifeng
 * @Date 2019/3/21 9:14
 **/
@Service
public class ActivityMultipleBizService {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private ActivityDetailBizService activityDetailBizService;
    @Autowired
    private CrowfundResourceBizService crowfundResourceBizService;
    @Autowired
    private IActivityService activityService;
    @Autowired
    private ActivityInfoBizService activityInfoBizService;
    @Autowired
    private FileBizService fileBizService;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private ITargetTemplateService targetTemplateService;
    @Autowired
    private IPackageCountService packageCountService;
    @Autowired
    private INotifySendService notifySendService;
    @Autowired
    private ICrowdfundEventService crowdfundEventService;

    /**
     * @param activity
     * @param activityDetail
     * @param crowdfundEvent
     * @param activityInput
     * @return void
     * @Author yifeng
     * @Description 项目保存
     * @Date 9:30 2019/3/21
     **/
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveActivity(Activity activity, ActivityDetail activityDetail, CrowdfundEvent crowdfundEvent,
                             ActivityInput activityInput) throws Exception {
        String memberId = activity.getMember();
        activity.setPrice(crowdfundEvent.getPrice());
        activity.setLimitNum(crowdfundEvent.getLimitNum());
        activity.setEndTime(crowdfundEvent.getEndTime());
        activity.setTitle(activity.getTitle().replace("\"", "“"));

        if (StringUtils.isNotEmpty(activity.getId())) {
            // 更新内容
            Activity t = activityService.get(activity.getId());
            BeanUtils.copyProperties(activity, t);
            activityService.update(t);// 保存
        } else {// 新增表单保存
            activity.setMember(memberId); // 当前用户
            activity.setIsCopartner(2); // 不是合伙人
            activity.setIsOpen(1); // 报名开启
            activity.setShareNum(0); // 分享数
            activity.setReadNum(0); // 阅读数
            activity.setJoinNum(0); // 报名数
            activity.setGoodNum(0); // 点赞数
            activity.setCheckStatus("1"); // 默认审核成功
            activity.setMicWebStatus(1); // 微网站效果
            activity.setInviteOnly(0); // 是否持邀请码参与
            activity.setIsAllowedOutside(0); // 是否允许在其它城市频道显示
            activity.setShowFront(1); // 显示在前端
            activity.setEditShare(YesNoStatus.NO_NEW.getCode());
            activity.setCrowdfundHintSwitch(YesNoStatus.NO.getCode());
            activityService.insert(activity);// 保存
        }

        /************* 详情 ****************/
        activityDetailBizService.saveBiz(activity.getId(), activityDetail);
        crowfundResourceBizService.saveResourceBiz(activity.getId(), activityInput.getPicList(), activityInput.getVideoList(), memberId);

        activityInfoBizService.saveBiz(activity.getId());

        try {
            String filePath = fileBizService.getUploadCIPath(memberId, "zcActivity");
            /*** 众筹联合发起二维码 ***/
            String dyFileName = "dy_" + activity.getId();
            String dyContent = "project/target_sponsor_multi.html?id=" + activity.getId();
            fileBizService.uploadCloudOut(dyFileName, filePath, dyContent, memberId);

            /*** 众筹项目详情二维码 ***/
            String xqFileName = "detail_" + activity.getId();
            String detailContent = "project/target_multi_detail.html?id=" + activity.getId();
            fileBizService.uploadCloudOut(xqFileName, filePath, detailContent, memberId);
        } catch (Exception e) {
            logger.error("众筹项目二维码生成异常", e);
        }

        //修改project冗余字段title
        try {
            projectService.updateProjectTitle(activity.getId());
        } catch (Exception e) {
            logger.error("activity保存——————修改project冗余字段title异常", e);
        }
    }

    /**
     * @param projectIds 众筹IDS
     * @param template   模板
     * @return boolean
     * @Author yifeng
     * @Description 保存并发送短信
     * @Date 17:12 2019/3/22
     **/
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean sendAndSave(String projectIds, String activityId, String eventId, TargetTemplate template) {
        String createBy = null;
        if (StringUtils.isNotEmpty(activityId)) {
            Activity activity = activityService.get(template.getTargetId());
            if (null == activity) {
                throw new BusinessException("找不到众筹项目");
            }
            createBy = activity.getMember();
        } else if (StringUtils.isNotEmpty(eventId)) {
            CrowdfundEvent crowdfundEvent = crowdfundEventService.get(eventId);
            if (null == crowdfundEvent) {
                throw new BusinessException("找不到众筹主題");
            }
            createBy = crowdfundEvent.getCreateBy();
        }
        //保存
        template.setId(null);
        template.setInitiatorId(createBy);
        Date now = new Date();
        template.setCreateDate(now);
        template.setUpdateDate(now);
        template.setSendTime(now);
        targetTemplateService.insert(template);

        PackageCount packageCount = packageCountService.getUnique(new PackageCount(createBy, TargetType.PUSH_SMS.getCode()));
        if (packageCount != null && YesNoStatus.YES.getCode().equals(packageCount.getIsOpen())) {
            Integer spareNum = packageCountService.getSpareNum(packageCount.getTotalNum(), packageCount.getUseNum());
            template.setSpareNum(spareNum);
        }

        return notifySendService.multipleProjectSend(template.getTargetId(), createBy,
                template, InstanceWay.SYSTEM.getName(), projectIds);
    }
}
